/**
 * Created by Administrator on 2017/5/11.
 */

var pool = require('../../app_server/dao/DBConnectPool');
var async = require('async');
var tool = require('../../common/utils/appUtils');
var redistool = require('../../common/utils/redistools');
var moment = require('moment');

module.exports = {

    getRandomMoney: function (params, callback) {
        var remainSize;
        var remainMoney;
        if (remainSize == 1) {
            remainSize--;
            // callback
            return Math.round(remainMoney * 100) / 100
        }
        var min = 0.01;
        var max = remainMoney / remainSize * 2;

        var random = Math.random() * max;
        var money = random <= min ? 0.01 : random;
        money = Math.floor(money * 100) / 100;
        remainSize--;
        remainMoney -= money;
        return money
    },

    getRedBag: function (isUser,params, callback) {

        var vuser=isUser
        var that = this;
        var openid = params;
        var remainSize;
        var remainMoney;
        var moneylog;
        var id;

        // locker.acquire(function () {
        pool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                return callback(err, null);
            }
            connection.beginTransaction(function (err, result) {
                if (err) {
                    return callback(err, null);
                }
                /**
                 * 1.查表是否有红包，红包余额
                 * 2.查记录表中是否存在，存在不可继续
                 * 3.金额，包数减
                 * 4.日志表记录
                 */
                async.waterfall([
                    function (callback) {
                        connection.query("select * from redbag where isfinished=0", null, function (err, result) {
                            if (err) {
                                console.log("事务失败，" + 1 + "，ERROR：" + err);
                                throw err;
                            } else {
                                if (!result || result.length < 1) {
                                    callback(null, {isSuccess: false, message: "本次抢红包已结束，请等待下次"})
                                    // var err = new Error("本次抢红包已结束，请等待下次")
                                    // err.name = 'red'
                                    // throw err;
                                } else if (result.remainpackage == 0 || result.remainmoney == 0) {
                                    // var err = new Error("红包被抢光了")
                                    // err.name = 'red'
                                    // throw err;
                                    callback(null, {isSuccess: false, message: "红包被抢光了"})
                                } else {
                                    console.log('剩余红包数：', result[0].remainpackage)
                                    callback(null, {isSuccess: true, message: "", result: result[0]})
                                }
                            }
                        })
                    },
                    function (arg0, callback) {
                        arg = arg0.result;
                        if (!arg0.isSuccess) {
                            return callback(null, arg0)
                        }
                        connection.query("select * from redresult where rid=? and openid=? ", [arg.id, openid], function (err, result) {
                            if (err) {
                                console.log("事务失败，" + 1 + "，ERROR：" + err);
                                throw err;
                            } else {
                                if (result.length < 1) {
                                    callback(null, {isSuccess: true, message: "", result: arg})
                                } else {
                                    callback(null, {isSuccess: false, message: "您已抢过该红包！"})
                                }
                            }
                        })
                    },
                    function (arg0, callback) {
                        // 获得红包id，查询redis次数
                        if (!arg0.isSuccess) {
                            callback(null, arg0);
                            return;
                        }
                        var arg = arg0.result;
                        if (arg.id) {
                            var date = moment().format("MMDD").toString();
                            that.getValidTime(date + openid + arg.id, function (result) {
                                if (parseInt(result.result) <= 3) {
                                    callback(null, arg0);
                                } else {
                                    callback(null, {isSuccess: false, message: "今日该红包已超过3次，您今日抢红包的次数已用光！"})
                                }
                            })
                        } else {
                            callback(null, {isSuccess: false, message: "今日该红包已超过3次，您今日抢红包的次数已用光！000000000000"})
                        }
                    },
                    function (arg0, callback) {

                        if (!arg0.isSuccess) {
                            callback(null, arg0)
                            return;
                        }
                        //获得剩余金额和次数
                        var arg = arg0.result;
                        id = arg.id;
                        remainMoney = arg.remainmoney;
                        remainSize = arg.remainpackage;

                        if (remainSize == 1) {
                            remainSize--;
                            // callback
                            money = Math.round(remainMoney * 100) / 100;
                            remainMoney = 0;
                            moneylog = money;
                            connection.query("update redbag set isfinished=? where id=?", [1, id], function (err, result) {
                                if (err) {
                                    console.log("事务失败，" + 1 + "，ERROR：" + err);
                                    throw err;
                                } else {
                                    // money = Math.round(remainMoney * 100) / 100
                                    // return callback(null, {isSuccess: true, message: "", result: result})
                                }
                            })

                        } else if (remainSize > 1) {
                            var min = 0.01;
                            var max = remainMoney / remainSize * 2;
                            var random = Math.random() * max;
                            var money = random <= min ? 0.01 : random;
                            money = Math.floor(money * 100) / 100;
                            money = money > remainMoney ? remainMoney - 0.01 : money;
                            remainSize--;
                            remainMoney -= money;
                            //数据更新
                            moneylog = money;
                        }
                        connection.query("update redbag set remainmoney=?, remainpackage=? where id=?", [remainMoney, remainSize, id], function (err, result) {
                            if (err) {
                                console.log("事务失败，" + 1 + "，ERROR：" + err);
                                throw err;
                            } else {
                                return callback(null, {isSuccess: true, message: "", result: result})
                            }
                        })

                    },
                    function (arg1, callback) {
                        if (!arg1.isSuccess) {
                            callback(null, arg1)
                            return
                        }
                        connection.query("insert into redresult (openid,money,rid,createtime) values(?,?,?,now()) ", [openid, moneylog, id], function (err, result) {
                            if (err) {
                                console.log("事务失败，" + 1 + "，ERROR：" + err);
                                throw err;
                            } else {
                                if (result.affectedRows == 1) {
                                    if(vuser) {
                                        return callback(null, {isSuccess: true, message: '您已抽中红包，金额为：' + moneylog+'元。'})
                                    }else{
                                        return callback(null, {isSuccess: true, message: '您已抽中红包，金额为：' + moneylog+'元。如未注册会员，请点击'+'<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf378ab4ba9fb3da&redirect_uri=http%3A%2F%2F1a65369r25.iask.in%2Fmemberhome&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect">注册</a> '})
                                    }
                                }
                            }
                        })
                    }
                ], function (err, result) {
                    console.log("transaction error: " + err);
                    if (err) {

                        connection.rollback(function (err) {
                            console.log("transaction error: " + err);
                            connection.release();
                            return callback(err, null);
                        });

                    } else {
                        connection.commit(function (err, info) {
                            console.log("transaction info: " + JSON.stringify(info));
                            if (err) {
                                console.log("执行事务失败，" + err);
                                connection.rollback(function (err) {
                                    console.log("transaction error: " + err);
                                    connection.release();
                                    return callback(err, null);
                                });
                            } else {
                                connection.release();
                                return callback({isSuccess: true, message: result.message});
                            }
                        })
                    }
                })
            });
        });
    },
    validUser: function (params, callback) {
        tool.baseDao('validuser', 'select * from member_user where openid=?', params, function (result) {
            if(result.isSuccess&&result.rows.length>0) {
                callback({isSuccess:true})
            }else{
                callback({isSuccess:false})
            }

        })
    },
    getValidTime: function (key, callback) {
        redistool.get(key, function (err, result) {
            if (err) {
                callback({isSuccess: false})
            } else {
                if (result) {
                    callback({isSuccess: true, result: result})
                    redistool.set(key, 1 + parseInt(result), 24 * 60 * 60, function (result) {
                        // callback(result);
                    })
                } else {
                    callback({isSuccess: true, result: 0})
                    redistool.set(key, 1, 24 * 60 * 60, function (result) {
                        // callback(result);
                    })
                }

            }
        })
    }
}


